package com.itheima.controller;


import com.itheima.bean.exception.BusinessException;
import com.itheima.bean.vo.*;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user") //请求路径
@CrossOrigin
public class UserController {
    @Autowired
    private  UserService userService;
    /**
     * 分页查询用户数据
     *
     * @param currentPage 页码
     * @param pageSize    每页条数
     * @return
     */
    @GetMapping("/{currentPage}/{pageSize}")
    public Result selectUserByPage(@PathVariable Integer currentPage,
                                   @PathVariable Integer pageSize) {

        if (pageSize <=0){
            throw  new BusinessException(Code.BUSINESS_ERR,"每页查询条数不能小于0");
        }


    //创建分页对象
        Pagination pagination = new Pagination();
        pagination.setCurrentPage(currentPage);
        pagination.setPageSize(pageSize);

        //调用业务功能：用户分页查询
        PageBean pageBean = userService.queryUserByPage(pagination);

        //创建响应结果对象（把响应的结果封装到该对象中）
        Result responseResult = new Result(Code.GET_ERR, "查询失败");
        //业务逻辑判断：业务层执行结果是否成功
        if (pageBean != null){
            //把查询的结果封装到响应对象
            responseResult= new Result(Code.GET_OK, pageBean, "查询成功");
        }
        return responseResult;
    }

    /**
     * 添加用户
     *
     * @param user 前端传递的请求参数对象：要添加的用户
     * @return
     */
    @PostMapping
    public Result addUser(@RequestBody  AddUser user) {

        //调用业务层：添加用户
        boolean result = userService.addUserAndRole(user);
        //响应结果对象
        Result responseResult = new Result(Code.SAVE_ERR, "保存失败");
        if (result){
            responseResult = new Result(Code.SAVE_OK,result,"保存成功");
        }
        return responseResult;
    }

    @DeleteMapping("/{id}")
    public Result deleteUser(@PathVariable Integer id) {
        boolean result= userService.deleteUser(id);
        Result responseResult = new Result(Code.DELETE_ERR, "删除失败");
        if (result){
            responseResult = new Result(Code.DELETE_OK,result,"删除成功");
        }
        return responseResult;
    }
    @PutMapping
    public Result updateUser(@RequestBody UpdateUser user) {
        boolean result= userService.updateUserRole(user);
        Result responseResult = new Result(Code.UPDATE_ERR, "删除失败");
        if (result){
            responseResult = new Result(Code.UPDATE_OK,result,"删除成功");
        }
        return responseResult;
    }
}
